package com.nbsaas.boot.controller.data.handle;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.nbsaas.boot.data.ext.apis.ResultHandleWork;
import com.nbsaas.boot.rest.request.ResultHandleObject;
import com.nbsaas.boot.rest.request.ResultHandleParam;
import com.nbsaas.boot.rest.response.MapResponse;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class HttpJsonHandle implements ResultHandleWork {
    @Override
    public void handle(ResultHandleObject handleObject, Map<String, Object> requestParam, MapResponse mapResponse) {
        String url = handleObject.getModel();
        if (!StringUtils.hasText(url)) {
            return;
        }

        HttpRequest httpRequest = HttpRequest.post(url);
        httpRequest.contentType("application/json");
        httpRequest.charset("utf-8");

        Map<String, Object> request = new HashMap<>();
        List<ResultHandleParam> params = handleObject.getParams();
        if (params != null) {
            for (ResultHandleParam param1 : params) {
                String name = param1.getParam();
                String type = param1.getType();
                String requestKey = param1.getRequestKey();
                if (!StringUtils.hasText(requestKey)) {
                    requestKey = name;
                }
                if ("result".equals(type)) {
                    request.put(requestKey, mapResponse.get(name));
                } else if ("value".equals(type)) {
                    request.put(requestKey, name);
                } else {
                    request.put(requestKey, requestParam.get(name));
                }
            }
        }

        httpRequest.bodyText(JSON.toJSONString(request), "application/json", "utf-8");


        HttpResponse response = httpRequest.send();

        if (response.statusCode() == 200) {
            response.charset("utf-8");
            JSONObject json = JSON.parseObject(response.bodyText());
            if ("single".equals(handleObject.getResultType())) {
                mapResponse.putAll(json);
            } else {
                mapResponse.put(handleObject.getResultKey(), json);
            }
        }
    }
}
